package com.tssup.fesco.service.impl;

import java.util.List;

import com.tssup.fesco.sales.goods.persistent.mapper.RGoodsspecificationParamMapper;
import com.tssup.fesco.sales.goods.persistent.pojo.RGoodsSpecificationParam;
import com.tssup.fesco.search.dao.ESClient;
import com.tssup.fesco.service.UpdateSpecParamService;
import com.tssup.fesco.util.TaskLogger;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * Created by jiashen on 17-6-19.
 */
@Service
public class UpdateSpecParamServiceImpl implements UpdateSpecParamService {
    private final String indexName;
    private final String specParamTypeName;
    private final Client client;

    @Autowired
    private TaskLogger taskLogger;

    @Autowired
    private RGoodsspecificationParamMapper specificationParamMapper;

    public UpdateSpecParamServiceImpl(Environment env, ESClient esClient) {
        super();
        indexName = env.getProperty("elasticsearch.searchArgs.indexName");
        specParamTypeName = env.getProperty("elasticsearch.searchArgs.specParamTypeName");
        client = esClient.getESClient();
    }

    @Override
    public void updateSpecParam() throws Exception {
        taskLogger.info("Updating spec param...");
        List<RGoodsSpecificationParam> allSpecParam = specificationParamMapper.selectAllDataForSearch();

        BulkRequestBuilder bulkRequest = client.prepareBulk();

        for (RGoodsSpecificationParam spceParam : allSpecParam) {
            bulkRequest.add(
                client.prepareIndex(indexName, specParamTypeName, spceParam.getParamId().toString())
                    .setSource(jsonBuilder()
                        .startObject()
                        .field("param_id", spceParam.getParamId())
                        .field("specification_id", spceParam.getSpecificationId())
                        .endObject()
                    ));
        }

        BulkResponse bulkResponse = bulkRequest.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            taskLogger.error("Update spec param get error: " + bulkResponse.buildFailureMessage());
            throw new Exception("Update spec param get error: " + bulkResponse.buildFailureMessage());
        }
    }
}
